import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';

class DatePicker extends StatefulWidget {
  const DatePicker({Key? key}) : super(key: key);

  @override
  _DatePickerState createState() => _DatePickerState();
}

class _DatePickerState extends State<DatePicker> {
  DateTime _nowDate=DateTime.now();
  var _nowTime=TimeOfDay(hour: 12, minute: 30);

  //日期 2021-11-29
  _showDatePicker() async{
    //第一种方法
    /*showDatePicker(
      context: context,
      initialDate:_nowDate,
      firstDate: DateTime(1980),
      lastDate: DateTime(2100),
    ).then((value){
      print(value);
    });*/

    //第二种方法  类的async和await配合使用,然后结合setState使用
    var result=await showDatePicker(
      context: context,
      initialDate:_nowDate,
      firstDate: DateTime(1980),
      lastDate: DateTime(2100),
      // locale: Locale('zh'),
    );
    print(result);
    setState(() {
      this._nowDate=result!;
    });
  }

  //时间 12:30
  _showTimePicker() async{
    var time = await showTimePicker(
      context: context,
      initialTime: _nowTime,
    );
    // Locale:Locale('zh');
    setState(() {
      this._nowTime=time!;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('日期'),
      ),
      body: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              InkWell(
                child:Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("${formatDate(_nowDate, [yyyy, '年', mm, '月', dd ,'日'])}"),
                    // Text(formatDate(_nowDate, [yyyy, '年', mm, '月', dd ,'日'])),这样也行
                    Icon(Icons.arrow_drop_down),
                  ],
                ),
                onTap:_showDatePicker,
              ),
              InkWell(
                child:Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("${_nowTime.format(context)}"),
                    Icon(Icons.arrow_drop_down),
                  ],
                ),
                onTap:_showTimePicker,
              ),
            ],
          ),
        ],
      ),
    );
  }
}
